import CodeBlock from "../../../component/CodeBlock";

function Performance() {
    const useMemoCode = `
// useMemo 示例 - 缓存计算结果
import React, { useMemo, useState } from 'react';

function ExpensiveComponent({ items }) {
  const expensiveValue = useMemo(() => {
    // 昂贵的计算操作
    return items.reduce((acc, item) => {
      return acc + item.value * item.multiplier;
    }, 0);
  }, [items]); // 只有当items变化时才重新计算

  return <div>计算结果: {expensiveValue}</div>;
}
`;

    const memoCode = `
// React.memo 示例 - 避免不必要的组件重渲染
import React, { memo, useState } from 'react';

// 使用memo包装组件
const ChildComponent = memo(({ title, data }) => {
  console.log('ChildComponent 渲染');
  return (
    <div>
      <h3>{title}</h3>
      <p>{data.content}</p>
    </div>
  );
});

function ParentComponent() {
  const [count, setCount] = useState(0);
  const [userData] = useState({ content: '用户数据' });

  return (
    <div>
      <button onClick={() => setCount(count + 1)}>
        计数: {count}
      </button>
      {/* 当count变化时，ChildComponent不会重新渲染 */}
      <ChildComponent title="子组件" data={userData} />
    </div>
  );
}
`;

    const useCallbackCode = `
// useCallback 示例 - 缓存函数引用
import React, { useCallback, useState } from 'react';

function ParentComponent() {
  const [count, setCount] = useState(0);

  // 使用useCallback缓存函数，避免子组件不必要的重渲染
  const handleClick = useCallback((value) => {
    console.log('点击事件处理', value);
  }, []); // 依赖项为空数组，函数永远不会重新创建

  return (
    <div>
      <button onClick={() => setCount(count + 1)}>
        计数: {count}
      </button>
      <ChildComponent onClick={handleClick} />
    </div>
  );
}
`;

    return (
        <div>
            <h2>性能优化Hooks</h2>
            <p>React提供了一些内置的Hooks来帮助我们优化组件性能：</p>
            
            <h3>1. useMemo</h3>
            <p>用于缓存计算结果，避免在每次渲染时都进行昂贵的计算。</p>
            <CodeBlock code={useMemoCode} />
            
            <h3>2. React.memo</h3>
            <p>高阶组件，用于避免函数组件在props没有改变时的不必要重渲染。</p>
            <CodeBlock code={memoCode} />
            
            <h3>3. useCallback</h3>
            <p>用于缓存函数引用，通常与React.memo配合使用，避免子组件因函数引用变化而重渲染。</p>
            <CodeBlock code={useCallbackCode} />
        </div>
    );
}

export default Performance;